package com.lkx.farmershop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.common.context.BaseContext;
import com.lkx.farmershop.mapper.TuanMapper;
import com.lkx.farmershop.model.dto.ExitGroupDto;
import com.lkx.farmershop.model.dto.HomeRequestDto;
import com.lkx.farmershop.model.dto.TuanDto;
import com.lkx.farmershop.model.entity.*;
import com.lkx.farmershop.model.vo.*;
import com.lkx.farmershop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * (Tuan)表服务实现类
 *
 * @author makejava
 * @since 2025-01-21 23:17:09
 */
@Service("tuanService")
@Slf4j
public class TuanServiceImpl extends ServiceImpl<TuanMapper, Tuan> implements TuanService {

    @Autowired
    private TuanImageService tuanImageService;
    @Autowired
    private TagService tagService;
    @Autowired
    private TagTuanService tagTuanService;
    @Autowired
    private IFarmerService farmerService;
    @Autowired
    private FollowService followService;
    @Autowired
    private TuanMemberService tuanMemberService;
    @Autowired
    private JoinReasonInfoService joinReasonInfoService;
    @Autowired
    private UserWordService userWordService;
    @Autowired
    private HotTagsService hotTagsService;

    /**
     * 保存草稿
     *
     * @param tuanDto
     * @return
     */
    @Override
    public ApiResult<String> saveDraft(TuanDto tuanDto) {
        Tuan tuan = tuanDto.getTuan();
        Long tuanId = tuan.getTuanId();
        //如果团Id已存在，则证明是从已存的草稿中再次保存草稿/发布，则需要先删除之前草稿再保存
        deleteOldTuanInfo(tuanId);

        if (tuan.getTuanTitle() == null || tuan.getTuanDetail() == null
                || tuan.getTuanTitle().isEmpty() || tuan.getTuanDetail().isEmpty()) {
            return ApiResult.failed("组团标题和组团详情不能为空！");
        }
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            return ApiResult.failed("暂存失败");
        }
        tuan.setUserId(userId);
        tuan.setTuanStatus(0);
        saveTuanInfo(tuanDto, tuan, userId);
        return ApiResult.success("保存草稿成功！");
    }

    /**
     * 发布组团
     *
     * @param tuanDto
     * @return
     */
    @Override
    public ApiResult<String> sendTuan(TuanDto tuanDto) {

        Tuan tuan = tuanDto.getTuan();
        Long tuanId = tuan.getTuanId();
        deleteOldTuanInfo(tuanId);

        if (tuan.getTuanTitle() == null || tuan.getTuanDetail() == null
                || tuan.getTuanTitle().isEmpty() || tuan.getTuanDetail().isEmpty()) {
            return ApiResult.failed("组团标题和组团详情不能为空！");
        }

        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            return ApiResult.failed("发布失败");
        }
        tuan.setUserId(userId);
        tuan.setTuanStatus(1);
        tuan.setSendTime(LocalDateTime.now());


        //把组团信息保存到数据库中
        saveTuanInfo(tuanDto, tuan, userId);
        return ApiResult.success("发布组团成功！");
    }

    private void deleteOldTuanInfo(Long tuanId) {
        //如果团Id已存在，则证明是从已存的草稿中再次保存草稿/发布，则需要先删除之前草稿再保存
        if (tuanId != null) {
            //删除组团信息对应图片
            LambdaQueryWrapper<TuanImage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TuanImage::getTuanId, tuanId);
            tuanImageService.remove(queryWrapper);
            //删除标签
            LambdaQueryWrapper<TagTuan> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(TagTuan::getTuanId, tuanId);
            List<TagTuan> list = tagTuanService.list(queryWrapper2);
            //若标签没有其他组团引用，则直接删除标签
            list.stream().forEach(tagTuan -> {
                Long tagId = tagTuan.getTagId();
                LambdaQueryWrapper<TagTuan> qw = new LambdaQueryWrapper<>();
                qw.eq(TagTuan::getTagId, tagId);
                if (tagTuanService.count(qw) == 1) {
                    tagService.removeById(tagId);
                }
            });
            //删除标签与组团的联系
            tagTuanService.remove(queryWrapper2);

            //删除组团信息
            removeById(tuanId);
        }
    }

    /**
     * 获取组团信息列表
     *
     * @param userId
     * @return
     */
    @Override
    public ApiResult<List<DraftsVo>> getDrafts(Long userId) {
        LambdaQueryWrapper<Tuan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tuan::getUserId, userId);
        queryWrapper.eq(Tuan::getTuanStatus, 0);
        List<Tuan> list = list(queryWrapper);
        if (list == null) {
            return ApiResult.failed("暂无草稿");
        }

        List<DraftsVo> collect = list.stream().map(tuan ->
                        new DraftsVo(tuan.getTuanId(), tuan.getTuanTitle(), tuan.getTuanDetail()))
                .collect(Collectors.toList());

        // 翻转collect顺序
        java.util.Collections.reverse(collect);

        return ApiResult.success(collect);
    }

    /**
     * 获取我发布的组团信息列表
     *
     * @param userId
     * @return
     */
    @Override
    public ApiResult<List<DraftsVo>> getSend(Long userId) {
        LambdaQueryWrapper<Tuan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tuan::getUserId, userId);
        queryWrapper.eq(Tuan::getTuanStatus, 1).or().eq(Tuan::getTuanStatus, 2);
        List<Tuan> list = list(queryWrapper);
        if (list == null || list.isEmpty()) {
            return ApiResult.failed("暂无草稿");
        }

        List<DraftsVo> collect = list.stream().map(tuan ->
                        new DraftsVo(tuan.getTuanId(), tuan.getTuanTitle(), tuan.getTuanDetail(), tuan.getNeedAgree(), tuan.getQuestion()))
                .collect(Collectors.toList());

        // 翻转collect顺序
        java.util.Collections.reverse(collect);

        return ApiResult.success(collect);
    }

    @Override
    public ApiResult<List<JoinApplyVo>> getJoinInfo(Long tuanId) {
        //获取此组团的加入申请
        List<JoinReasonInfo> reasonInfos = joinReasonInfoService
                .lambdaQuery().eq(JoinReasonInfo::getTuanId, tuanId).list();
        if (reasonInfos == null || reasonInfos.isEmpty()) {
            return ApiResult.failed("暂无加入申请");
        }
        //获取前端需要的信息
        List<JoinApplyVo> joinApplyVos = reasonInfos.stream().map(joinReasonInfo -> {
            JoinApplyVo joinApplyVo = new JoinApplyVo();
            BeanUtils.copyProperties(joinReasonInfo, joinApplyVo);
            Farmer user = farmerService.lambdaQuery().eq(Farmer::getFarmerId, joinReasonInfo.getUserId()).one();
            joinApplyVo.setUserName(user.getName());
            joinApplyVo.setAvatar(user.getAvatar());
            return joinApplyVo;
        }).collect(Collectors.toList());

        // 翻转collect顺序
        java.util.Collections.reverse(joinApplyVos);
        return ApiResult.success(joinApplyVos);

    }

    @Override
    public ApiResult<UserHomeVo> getUserHome(Long theUserId, Long userId) {
        UserHomeVo userHomeVo = new UserHomeVo();
        //获取用户发布的的组团
        List<Tuan> tuanList = lambdaQuery()
                .eq(Tuan::getUserId, theUserId)
                .eq(Tuan::getTuanStatus, 1)
                .or()
                .eq(Tuan::getUserId, theUserId)
                .eq(Tuan::getTuanStatus, 2)
                .list();
        tuanList.forEach(tuan -> {
            GroupVo groupVo = new GroupVo();
            BeanUtils.copyProperties(tuan, groupVo);
            List<GroupVo> groupList = userHomeVo.getGroupList();
            groupList.add(groupVo);
            userHomeVo.setGroupList(groupList);
        });
        //获取前三章图片
        userHomeVo.getGroupList().forEach(groupVo -> {
            List<TuanImage> images = tuanImageService.lambdaQuery().eq(TuanImage::getTuanId, groupVo.getTuanId()).list();
            if (images != null && !images.isEmpty()) {
                List<String> threeImages = images.stream().limit(3).map(TuanImage::getImageUrl).collect(Collectors.toList());
                groupVo.setThreeImages(threeImages);
            } else {
                groupVo.setThreeImages(new ArrayList<>());
            }
        });
        //获取用户信息
        Farmer theUser = farmerService.getById(theUserId);
        userHomeVo.setSimpleUserVo(new SimpleUserVo(theUser.getFarmerId(), theUser.getName(), theUser.getAvatar()));
        //获取用户关注、粉丝数
        Integer followCount = followService.lambdaQuery().eq(Follow::getUserid, theUserId).count();
        Integer fansCount = followService.lambdaQuery().eq(Follow::getFollowedUserid, theUserId).count();
        userHomeVo.setFollowAndFansCount(new FollowAndFansCount(followCount, fansCount));
        //是否关注了此用户
        LambdaQueryWrapper<Follow> fqw = new LambdaQueryWrapper<>();
        fqw.eq(Follow::getUserid, userId).eq(Follow::getFollowedUserid, theUserId);
        userHomeVo.setIsFollowed(followService.getOne(fqw) != null);
        //翻转collect顺序
        java.util.Collections.reverse(userHomeVo.getGroupList());
        return ApiResult.success(userHomeVo);
    }

    /**
     * 根据id获取组团详细信息
     *
     * @param tuanId
     * @return
     */
    @Override
    public ApiResult<TuanDto> getTuanById(Long tuanId) {

        if (tuanId == null) {
            return ApiResult.failed("获取失败");
        }
        Tuan tuan = getById(tuanId);
        TuanDto tuanDto = new TuanDto();
        //保存组团信息
        tuanDto.setTuan(tuan);

        //保存标签信息
        List<TagTuan> tagTuanList = tagTuanService.list(new LambdaQueryWrapper<TagTuan>().eq(TagTuan::getTuanId, tuanId));
        if (tagTuanList != null && !tagTuanList.isEmpty()) {
            List<Long> collect = tagTuanList.stream().map(TagTuan::getTagId).collect(Collectors.toList());
            List<Tag> tagList = tagService.listByIds(collect);
            String[] tagNames = tagList.stream().map(Tag::getTagname).toArray(String[]::new);
            tuanDto.setTagName(tagNames);
        }

        //保存图片信息
        List<TuanImage> imagesList = tuanImageService.list(new LambdaQueryWrapper<TuanImage>().eq(TuanImage::getTuanId, tuanId));
        if (imagesList != null && !imagesList.isEmpty()) {
            String[] images = imagesList.stream().map(TuanImage::getImageUrl).toArray(String[]::new);
            tuanDto.setImages(images);
        }

        return ApiResult.success(tuanDto);
    }

    @Override
    public ApiResult<String> deleteDraft(Long tuanId) {

        if (tuanId == null) {
            return ApiResult.failed("删除失败");
        }

        deleteOldTuanInfo(tuanId);
        return ApiResult.success("删除成功");

    }

    /**
     * 主页获取组团信息
     *
     */
    @Override
    public ApiResult<List<GroupVo>> getGroupList(HomeRequestDto homeRequestDto) {
        Long userId = homeRequestDto.getUserId();
        String selectedTag = homeRequestDto.getSelectedTag();
        Integer page = homeRequestDto.getPage();
        Integer pageSize = homeRequestDto.getPageSize();
        Double distanceValue = homeRequestDto.getDistanceValue();
        LocalDateTime startTime = homeRequestDto.getStartTime();
        LocalDateTime endTime = homeRequestDto.getEndTime();

        //若用户选择推荐
        if (selectedTag.equals("推荐")) {
            page = 1;
            pageSize = 20;
            //获取用户关键词，若不足20个，则从热门标签获取
            List<UserWord> wordList = userWordService.lambdaQuery()
                    .eq(UserWord::getUserId, userId)
                    .last("LIMIT 20")
                    .list();
            List<String> selectedTagList = wordList.stream().map(UserWord::getWord).collect(Collectors.toList());


            if (selectedTagList.size() < 20) {
                List<HotTags> hotTags = hotTagsService.lambdaQuery()
                        .orderByDesc(HotTags::getId)
                        .last("LIMIT 20")
                        .list();

                for(int i = 0; selectedTagList.size() < 20; i++){
                    HotTags hotTags1 = hotTags.get(i);
                    //查询标签名
                    Tag tag = tagService.getById(hotTags1.getTagId());
                    selectedTagList.add(tag.getTagname());
                }
            }

            //生成20以内的随机整数
            int randomNumber = (int) (Math.random() * 20);
            selectedTag = selectedTagList.get(randomNumber);

        }

        // 获取用户位置
        Farmer user = farmerService.getById(userId);
        double userLongitude = user.getLongitude();
        double userLatitude = user.getLatitude();

        // 从组团标题与详情查找
        LambdaQueryWrapper<Tuan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Tuan::getTuanTitle, selectedTag)
                .eq(Tuan::getTuanStatus, 1)
                .or()
                .like(Tuan::getTuanDetail, selectedTag)
                .eq(Tuan::getTuanStatus, 1)
                .orderByDesc(Tuan::getSendTime);

        // 添加startTime和endTime的过滤条件
        if (startTime != null) {
            queryWrapper.gt(Tuan::getBeginTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.lt(Tuan::getEndTime, endTime);
        }

        queryWrapper.last("LIMIT " + (page - 1) * pageSize + ", " + pageSize);

        List<GroupVo> groupVoList = list(queryWrapper)
                .stream()
                .filter(tuan -> distanceValue == null || calculateDistance(userLongitude, userLatitude, tuan.getLongitude(), tuan.getLatitude()) <= distanceValue)
                .map(this::apply)
                .collect(Collectors.toList());

        // 从标签查找
        Tag tag = tagService.lambdaQuery().eq(Tag::getTagname, selectedTag).one();
        if (tag != null) {
            // 获取标签的组团
            LambdaQueryWrapper<TagTuan> tagTuanQueryWrapper = new LambdaQueryWrapper<>();
            tagTuanQueryWrapper.eq(TagTuan::getTagId, tag.getId())
                            .eq(TagTuan::getFakeHide, false)
                            .orderByDesc(TagTuan::getId)
                            .last("LIMIT " + (page - 1) * pageSize + ", " + pageSize);

            List<Long> tuanIds = tagTuanService.list(tagTuanQueryWrapper)
                .stream()
                .map(TagTuan::getTuanId)
                .collect(Collectors.toList());

            // 获取组团信息
            if (!tuanIds.isEmpty()) {
                LambdaQueryWrapper<Tuan> tuanQueryWrapper = new LambdaQueryWrapper<>();
                tuanQueryWrapper.in(Tuan::getTuanId, tuanIds)
                            .eq(Tuan::getTuanStatus, 1);

                // 添加startTime和endTime的过滤条件
                if (startTime != null) {
                    tuanQueryWrapper.gt(Tuan::getBeginTime, startTime);
                }
                if (endTime != null) {
                    tuanQueryWrapper.lt(Tuan::getEndTime, endTime);
                }

                List<GroupVo> groupVoList2 = list(tuanQueryWrapper)
                        .stream()
                        .filter(tuan -> distanceValue == null || calculateDistance(userLongitude, userLatitude, tuan.getLongitude(), tuan.getLatitude()) <= distanceValue)
                        .map(this::apply)
                        .collect(Collectors.toList());

                // 翻转 collect 顺序
                java.util.Collections.reverse(groupVoList2);
                groupVoList.addAll(groupVoList2);
            }
        }

        return ApiResult.success(groupVoList);
    }

    /**
     * 计算两个经纬度点之间的距离（单位：千米）
     *
     * @param lon1 第一个点的经度
     * @param lat1 第一个点的纬度
     * @param lon2 第二个点的经度
     * @param lat2 第二个点的纬度
     * @return 两点之间的距离（千米）
     */
    private double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
        final int R = 6371; // 地球半径（千米）

        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double distance = R * c;
        // 格式化距离到小数点后一位
        return Double.parseDouble(String.format("%.2f", distance));
    }

    @Override
    public ApiResult<GroupDetailVo> getGroupById(Long tuanId, Long userId) {
        //添加用户关键词
        CollectServiceImpl.addUserWord(tuanId, userId, tagTuanService, tagService, userWordService);

        if (tuanId == null) {
            return ApiResult.failed("获取失败");
        }
        Tuan tuan = getById(tuanId);
        //更新浏览量
        if (!Objects.equals(userId, tuan.getUserId())){
            tuan.setViewCount(tuan.getViewCount() + 1);
            updateById(tuan);
        }

        GroupDetailVo groupDetailVo = new GroupDetailVo();

        //获取组团发布者信息
        LambdaQueryWrapper<Farmer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Farmer::getFarmerId, tuan.getUserId());
        Farmer one = farmerService.getOne(queryWrapper);
        groupDetailVo.setTheUserId(one.getFarmerId());
        groupDetailVo.setTheUserName(one.getName());
        if (one.getAvatar() == null) {
            groupDetailVo.setTheUserAvatar("");
        } else {
            groupDetailVo.setTheUserAvatar(one.getAvatar());
        }

        //获取当前用户对组团发布者的关注状态
        LambdaQueryWrapper<Follow> fqw = new LambdaQueryWrapper<>();
        fqw.eq(Follow::getUserid, userId).eq(Follow::getFollowedUserid, tuan.getUserId());
        groupDetailVo.setIsFollowed(followService.getOne(fqw) != null);

        //保存组团信息
        groupDetailVo.setTuan(tuan);

        //保存标签信息
        List<TagTuan> tagTuanList = tagTuanService.list(new LambdaQueryWrapper<TagTuan>().eq(TagTuan::getTuanId, tuanId));
        if (tagTuanList != null && !tagTuanList.isEmpty()) {
            List<Long> collect = tagTuanList.stream().map(TagTuan::getTagId).collect(Collectors.toList());
            List<Tag> tagList = tagService.listByIds(collect);
            String[] tagNames = tagList.stream().map(Tag::getTagname).toArray(String[]::new);
            groupDetailVo.setTagName(tagNames);
        }

        //保存图片信息
        List<TuanImage> imagesList = tuanImageService.list(new LambdaQueryWrapper<TuanImage>().eq(TuanImage::getTuanId, tuanId));
        if (imagesList != null && !imagesList.isEmpty()) {
            String[] images = imagesList.stream().map(TuanImage::getImageUrl).toArray(String[]::new);
            groupDetailVo.setImages(images);
        }

        return ApiResult.success(groupDetailVo);
    }

    @Override
    public ApiResult<String> joinGroup(JoinReasonInfo joinReasonInfo) {
        Long tuanId = joinReasonInfo.getTuanId();
        Long userId = joinReasonInfo.getUserId();
        String joinReason = joinReasonInfo.getJoinReason();

        //添加用户关键词
        CollectServiceImpl.addUserWord(tuanId, userId, tagTuanService, tagService, userWordService);

        //若该用户已加入该团，则返回提示
        if (tuanMemberService.getOne(new LambdaQueryWrapper<TuanMember>()
                .eq(TuanMember::getTuanId, tuanId)
                .eq(TuanMember::getMemberId, userId)) != null) {
            log.info("您已加入该组团");
            return ApiResult.failed("您已加入该组团");
        }
        //若该用户已发出加入验证申请，则返回提示
        List<JoinReasonInfo> reasonInfos = joinReasonInfoService.lambdaQuery().eq(JoinReasonInfo::getTuanId, tuanId)
                .eq(JoinReasonInfo::getUserId, userId)
                .list();
        if (reasonInfos != null && !reasonInfos.isEmpty()) {
            log.info("您已发出加入申请");
            return ApiResult.failed("您已发出过申请，请等待发起者同意");
        } else {
            Tuan tuan = getById(tuanId);
            if (!tuan.getNeedAgree()) {
                //若该组团加入无需发起者同意，则直接加入
                tuan.setJoinPeople(tuan.getJoinPeople() + 1);
                updateById(tuan);
                tuanMemberService.save(new TuanMember(tuanId, userId, false));
                if (tuan.getJoinPeople() >= tuan.getRequiredPeople()) {
                    //组团人数达到需要人数时，自动结束组团
                    //状态设置为2后，不会被用户查询到该组团信息
                    tuan.setTuanStatus(2);
                    updateById(tuan);
                }
                return ApiResult.success("加入组团成功");
            } else {
                //若需发起者同意，则先把申请加入JoinReasonInfo表
                JoinReasonInfo j = new JoinReasonInfo();
                j.setTuanId(tuanId);
                j.setUserId(userId);
                j.setJoinReason(joinReason);
                joinReasonInfoService.save(j);
                return ApiResult.success("申请已提交，请等待发起者同意");
            }

        }
    }

    @Override
    public ApiResult<List<DraftsVo>> getMyJoin(Long userId) {
        //获取用户所有加入的组团
        List<TuanMember> tuanMemberList = tuanMemberService.lambdaQuery().eq(TuanMember::getMemberId, userId)
                .eq(TuanMember::getIsInitiator, false)
                .list();
        if (tuanMemberList == null || tuanMemberList.isEmpty()) {
            return ApiResult.failed("暂无加入的组团");
        }
        //获取组团id
        List<Long> tuanIdList = tuanMemberList.stream().map(TuanMember::getTuanId)
                .collect(Collectors.toList());

        //转化成DraftsVo
        List<DraftsVo> draftsVoList = tuanIdList.stream().map(tuanId -> {
            Tuan tuan = getById(tuanId);
            return new DraftsVo(tuan.getTuanId(), tuan.getTuanTitle(), tuan.getTuanDetail());
        }).collect(Collectors.toList());

        // 翻转collect顺序
        java.util.Collections.reverse(draftsVoList);
        return ApiResult.success(draftsVoList);
    }

    @Override
    public ApiResult<String> exitGroup(ExitGroupDto exitGroupDto) {
        Long tuanId = exitGroupDto.getTuanId();
        Long userId = exitGroupDto.getUserId();
        TuanMember one = tuanMemberService.getOne(new LambdaQueryWrapper<TuanMember>()
                .eq(TuanMember::getTuanId, tuanId)
                .eq(TuanMember::getMemberId, userId));
        if (one == null) {
            log.info("您已退出该组团");
            return ApiResult.failed("您已退出该组团");
        }
        tuanMemberService.removeById(one);
        return ApiResult.success("退出组团成功");
    }

    @Override
    public ApiResult<String> endTuan(Long tuanId) {
        Tuan tuan = getById(tuanId);
        tuan.setTuanStatus(2);
        updateById(tuan);
        return ApiResult.success("组团已结束");
    }


    private void saveTuanInfo(TuanDto tuanDto, Tuan tuan, Long userId) {
        tuan.setJoinPeople(0);
        //若是发布的组团，且设置了加入需要验证，但验证问题为空，则设置问题为“无”
        if (tuan.getTuanStatus() == 1 && tuan.getNeedAgree() &&
                (tuan.getQuestion() == null || tuan.getQuestion().trim().isEmpty())) {
            tuan.setQuestion("无");
        }
        //保存组团信息
        save(tuan);
        Long tuanId = tuan.getTuanId();
        //保存组团成员信息
        if (tuan.getTuanStatus() == 1) {
            tuanMemberService.save(new TuanMember(tuanId, userId, true));
        }

        //保存标签信息
        String[] tagNames = tuanDto.getTagName();
        if (tagNames != null) {
            for (String tagName : tagNames) {
                LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Tag::getTagname, tagName);
                Tag tag = tagService.getOne(queryWrapper);
                if (tag == null) {
                    tag = new Tag();
                    tag.setTagname(tagName);
                    tag.setUsedCount(tag.getUsedCount() + 1);
                    tagService.save(tag);
                }
                tag.setUsedCount(tag.getUsedCount() + 1);
                tagService.updateById(tag);
                //设置fakeHide的值
                boolean fakeHide = tuan.getTuanTitle().contains(tagName) || tuan.getTuanDetail().contains(tagName);
                tagTuanService.save(new TagTuan(tag.getId(), tuanId, fakeHide));
            }
        }

        //保存图片信息
        String[] images = tuanDto.getImages();

        if (images != null) {
            for (String image : images) {
                TuanImage tuanImage = new TuanImage();
                tuanImage.setTuanId(tuanId);
                tuanImage.setImageUrl(image);
                tuanImageService.save(tuanImage);
            }
        }
    }

    private GroupVo apply(Tuan tuan) {
        GroupVo groupVo = new GroupVo();
        //设置组团信息
        BeanUtils.copyProperties(tuan, groupVo);
        //获取该组团的用户头像与昵称
        LambdaQueryWrapper<Farmer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Farmer::getFarmerId, tuan.getUserId());
        Farmer user = farmerService.getOne(queryWrapper);
        groupVo.setName(user.getName());
        groupVo.setAvatar(user.getAvatar());
        //获取前三张图片
        LambdaQueryWrapper<TuanImage> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(TuanImage::getTuanId, tuan.getTuanId());
        List<TuanImage> imageList = tuanImageService.list(qw2);
        if (imageList != null && !imageList.isEmpty()) {
            List<String> threeImages = imageList.stream().map(TuanImage::getImageUrl).limit(3).collect(Collectors.toList());
            groupVo.setThreeImages(threeImages);
        } else {
            groupVo.setThreeImages(new ArrayList<>());
        }

        return groupVo;
    }
}

